import Vue from 'vue'
import { Message } from 'element-ui'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false;


// 配置 Vue 插件 将 El 安装到 Vue 上
Vue.use(ElementUI);

// 引入 axios
import axios from 'axios';
// Vue 对象使用 axios
Vue.prototype.axios = axios;
Vue.prototype.$message = Message

Vue.prototype.axios.interceptors.request.use(
    config => {
      // 如果storage中存在token，请求时将token设置成请求头
      if (localStorage.getItem('token')) {
        config.headers.token = localStorage.getItem('token')
      }
      return config
    },
    error => {
      return Promise.reject(error)
    }
)

Vue.prototype.axios.interceptors.response.use(
    res => {
        // 当响应的类型为失败且信息为NOTLOGIN时
        if (res.data.code === 201) {
            // 清除本地账号信息
            localStorage.removeItem('token')
            Vue.prototype.$message({
                message: res.data.message,
                type: 'error'
            })
            // 跳转到登录界面
            setTimeout(() => {
                router.push('/login')
            }, 3000)
        } else {
            if (res.data.code !== 200) {
                Vue.prototype.$message({
                    message: res.data.message,
                    type: 'error'
                })
            }
        }
        return res
    },
    error => {
        console.log('err' + error)
        let {message} = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        window.ELEMENT.Message({
            message: message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)


new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');